/*
 * Jamus
 * Copyright (C) 2010 Jamus Team
 *
 * Jamus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Jamus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Jamus.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef __BACKEND_XMMS2_PLUGIN
#define __BACKEND_XMMS2_PLUGIN

#include <log4cxx/logger.h>
#include <xmmsclient/xmmsclient++.h>
#include <boost/thread.hpp>

#include "../Plugin.h"

namespace backend {
namespace xmms2 {

class Plugin : public backend::Plugin, private boost::noncopyable
{
public:
	Plugin(bool useSeekSignalPlaytimeWorkaround = true);
	virtual ~Plugin();

	virtual void run();
	virtual void cancel();

	/*
	 * Playback
	 */
	virtual PlaybackStatus getPlaybackStatus();
	virtual void play();
	virtual void play(int);
	virtual void playPause();
	virtual void pause();
	virtual void stop();

	virtual void nextTrack();
	virtual void prevTrack();
	virtual int getCurrentTrack();
	virtual boost::posix_time::time_duration getElapsed();
	virtual void seek(const boost::posix_time::time_duration&);

	/*
	 * Mixer
	 */
	virtual int getVolume();
	virtual void setVolume(int vol);

	/*
	 * Music library
	 */
	virtual const TrackList& getTrackList();

	/*
	 * Current playlist
	 */
	virtual const Playlist& getPlaylist();
	virtual void addToPlaylist(const std::string& fileName);
	virtual void removeFromPlaylist(int index);
	virtual void clearPlaylist();

private:
	void buildTrackFromId(Track& track, int id);
	void fetchPlaylistFromServer();

	bool onCurrentPosChanged(const Xmms::Dict&);
	bool onPlaylistChanged(const Xmms::Dict&);
	bool onPlaybackStatusChanged(const xmms_playback_status_t&);
	bool onVolumeChanged(const Xmms::Dict&);
	bool onPlaytimeChanged(const int&);

	static log4cxx::LoggerPtr logger;

	Xmms::Client xmms;
	boost::scoped_ptr<Xmms::Client> idleConnection;

	TrackList tracks;
	Playlist playlist;

	bool running;
	pthread_t runThread;

	// Signal that is to be sent to the thread in run() when cancel() is called
	static const int CANCEL_SIGNAL;

	boost::mutex mutex;

	int lastSignalledPlaytime;
	boost::posix_time::ptime timeOfLastPlaytimeSignal;
};

} // namespace mpd
} // namespace backend

#endif
